#!/bin/bash

# 项目启动脚本

echo "正在启动 Architecture Drawing Demo..."

# 启动后端服务
echo "启动后端服务 (Spring Boot)..."
cd "$(dirname "$0")"
mvn spring-boot:run > backend.log 2>&1 &
BACKEND_PID=$!
echo "后端服务 PID: $BACKEND_PID"

# 等待后端启动
echo "等待后端服务启动..."
sleep 15

# 检查后端是否正常启动
if curl -sf http://localhost:8080/actuator/health > /dev/null; then
    echo "✅ 后端服务启动成功 (http://localhost:8080)"
else
    echo "❌ 后端服务启动失败"
    kill $BACKEND_PID 2>/dev/null
    exit 1
fi

# 启动前端服务
echo "启动前端服务 (Vue 3)..."
cd frontend
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
npm run dev > ../frontend.log 2>&1 &
FRONTEND_PID=$!
echo "前端服务 PID: $FRONTEND_PID"

echo "等待前端服务启动..."
sleep 5

# 检查前端是否正常启动
if curl -sf http://localhost:5173/ > /dev/null; then
    echo "✅ 前端服务启动成功 (http://localhost:5173)"
else
    echo "❌ 前端服务启动失败"
    kill $BACKEND_PID $FRONTEND_PID 2>/dev/null
    exit 1
fi

echo ""
echo "🎉 项目启动完成！"
echo "📋 服务信息："
echo "  - 后端API: http://localhost:8080"
echo "  - 前端界面: http://localhost:5173"
echo "  - 健康检查: http://localhost:8080/actuator/health"
echo ""
echo "📝 进程信息："
echo "  - 后端进程: $BACKEND_PID"
echo "  - 前端进程: $FRONTEND_PID"
echo ""
echo "停止服务请运行: ./stop.sh"
echo "查看日志请运行: tail -f backend.log 或 tail -f frontend.log"

# 保存进程ID
echo $BACKEND_PID > .backend.pid
echo $FRONTEND_PID > .frontend.pid